package org.ocean.online.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.ocean.hibernate.BaseHibernateDao;
import org.ocean.online.sys.BusinessException;
import org.ocean.online.user.initdb.InitUserAction;
import org.ocean.online.utils.ParamUtil;
import org.ocean.online.wicket.BaseWebPage;

public class Login extends BaseWebPage{
	private static final long serialVersionUID = 9166959524900634709L;

	public Login(){
		Form<?> form = new Form("form");
		AjaxSubmitLink btn = new AjaxSubmitLink("ajaxSubmitBtn") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				try{
					Map<String, String> data = ParamUtil.toMap(form.getRequest().getPostParameters());
					Map<String, Object> user = login(data);
					InitUserAction.init(user);
					HttpServletRequest servletRequest = ((ServletWebRequest) getRequest()).getContainerRequest();
					servletRequest.getSession().setAttribute("user",user);
					target.appendJavaScript("window.location='workspace2'");
				}catch(BusinessException ex){
					target.appendJavaScript("alert('"+ex.getMessage()+"')");
				}
				catch(Exception ex){
					log.error("login exception",ex);
					target.appendJavaScript("alert('system exception "+ex.getMessage()+"')");
				}
			}
			
		};
		form.add(btn);
		
		add(form);
	}
	
	private Map<String,Object> login(Map<String,String> data){
		BaseHibernateDao dao = new BaseHibernateDao();
		Map<String,Object> user = (Map<String, Object>) dao.findUnique("from user where username=? ", new Object[]{data.get("username")});
		if(user==null){
			throw new BusinessException("用户名不存在");
		}
		if(!user.get("password").equals(data.get("password"))){
			throw new BusinessException("密码不正确");
		}
		return user;
	}
	
}
